/**
 * This example turns the ESP32 into a Bluetooth LE keyboard that writes the words, presses Enter, presses a media key and then Ctrl+Alt+Delete
 */
#include <BleKeyboard.h>
#include <WiFi.h>
#include <math.h>

#define interruptPin_A 21     //A相
#define interruptPin_B 22     //B相
#define interruptPin_SW 23    //按键
#define LED 2                 //LED

#define VOLUME_UP    1
#define VOLUME_DOWN  2
#define BRIGHT_UP    3
#define BRIGHT_DOWN  4

const MediaKeyReport KEY_MEDIA_BRIGHT_UP = {32, 0};
const MediaKeyReport KEY_MEDIA_BRIGHT_DOWN = {64, 0};

BleKeyboard bleKeyboard;

bool mode = 1;
uint8_t type = 0;

void handleInterrupt_A() {
  if (digitalRead(interruptPin_A) == LOW){   
    if (digitalRead(interruptPin_B) == LOW){//反转
      if(mode)
        type = VOLUME_DOWN;
      else
        type = BRIGHT_DOWN;
    }
    else if (digitalRead(interruptPin_B) == HIGH){//正转
      if(mode)
        type = VOLUME_UP;
      else
        type = BRIGHT_UP;
    }
    //while(!digitalRead(interruptPin_A));
  }
  else if(digitalRead(interruptPin_A) == HIGH){//正转
    if (digitalRead(interruptPin_B) == LOW){
      if(mode)
        type = VOLUME_UP;
      else
        type = BRIGHT_UP;
    }
    else if (digitalRead(interruptPin_B) == HIGH){//反转
      if(mode)
        type = VOLUME_DOWN;
      else
        type = BRIGHT_DOWN;
    }
    //while(digitalRead(interruptPin_A));
  }
}

void handleInterrupt_SW()
{
  mode = !mode;
  digitalWrite(LED,!digitalRead(LED));
  while(!digitalRead(interruptPin_SW));
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting BLE work!");
  pinMode(interruptPin_A, INPUT_PULLUP);
  pinMode(interruptPin_B, INPUT_PULLUP);
  pinMode(interruptPin_SW, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin_A), handleInterrupt_A, CHANGE);
  attachInterrupt(digitalPinToInterrupt(interruptPin_SW), handleInterrupt_SW, FALLING);
  pinMode(LED, OUTPUT);
  digitalWrite(LED,LOW);
  bleKeyboard.begin();
}

void loop() {
  if(bleKeyboard.isConnected()) {
    switch (type)
    {
    case VOLUME_UP:
      bleKeyboard.write(KEY_MEDIA_VOLUME_UP);
      bleKeyboard.write(KEY_MEDIA_VOLUME_UP);
      type = 0;
      break;
    case VOLUME_DOWN:
      bleKeyboard.write(KEY_MEDIA_VOLUME_DOWN);
      bleKeyboard.write(KEY_MEDIA_VOLUME_DOWN);
      type = 0;
      break;
    case BRIGHT_UP:
      bleKeyboard.write(KEY_MEDIA_BRIGHT_UP);
      bleKeyboard.write(KEY_MEDIA_BRIGHT_UP);
      type = 0;
      break;
    case BRIGHT_DOWN:
      bleKeyboard.write(KEY_MEDIA_BRIGHT_DOWN);
      bleKeyboard.write(KEY_MEDIA_BRIGHT_DOWN);
      type = 0;
      break;
    default:
      break;
    }
  }
  delay(50);
}
